
let bx = 1240 / device.width
let by = 2772 / device.height
//是否打开控制台
let isOpenConsole = false
//是否开启调试模式
let debugMode = false
//日志的最大行数
let maxLine = 7
//设置控制台
function init (params) {
    //获取悬浮窗权限
    auto.waitFor()
    //打开录屏权限
    getScreenCapture()
    //设置屏幕宽高
    setScreenMetrics(1240, 2772)
    if (params && params.isOpenConsole) {
        isOpenConsole = params.isOpenConsole
        setConsole()
    }
    if (params && params.debugMode) {
        debugMode = params.debugMode
    }
}


//打开快手指定用户的主页
function openHome (originalURL) {
    //打开状态
    let openState = false
    try {
        let d = getIdByUrl(originalURL)
        app.startActivity({
            data: `kwai://profile/${d}`,
        });
        openState = true
        sleep(2000)
        closeLinkPopup()
    } catch (error) {
        console.error('Invalid URL:', error);
        openState = false
    }
    return openState
}

//打开快手极速版指定用户的主页
function openHome2 (originalURL) {
    //打开状态
    let openState = false
    try {
        let d = getIdByUrl(originalURL)
        app.startActivity({
            data: `ksnebula://profile/${d}`,
        });
        openState = true
        sleep(2000)
        closeLinkPopup()
    } catch (error) {
        console.error('Invalid URL:', error);
        openState = false
    }
    return openState
}

//关闭链接弹窗
function closeLinkPopup () {
    //弹窗关键字
    let popupKeywords = ["同意并继续","同意,并领新手红包", "去看看","我知道了","稍后","取消","忽略"]
    //遍历关键字
    for (let i = 0; i < popupKeywords.length; i++) {
        if (text(popupKeywords[i]).exists()) {
            click(popupKeywords[i])
            sleep(2000)
        }
    }
}

//通过链接获取id
function getIdByUrl (originalURL) {
    try {
        var r = http.get(originalURL);
        let url = r.url
        const regex = /[?&]shareObjectId=([^&]*)/;
        const match = url.toString().match(regex);
        // 如果匹配成功，返回值，否则返回null
        let d = match ? decodeURIComponent(match[1]) : null;
        return d
    } catch (error) {
        console.error('Invalid URL:', error);
        return null
    }
}

//搜索用户
function searchUser (userName) {
    app.startActivity({
        data: `kwai://search?keyword=${userName}`,
    });
    sleep(2000)
    closeLinkPopup()
    click("搜索")
}

//进入抖音首页
function enterDouYinIndex () {
    if (tool.getText('首页') !== null && tool.getText('消息') !== null) {
        tool.log("进入首页")
        if (tool.clickTextByScreenCapture("首页")) {
            tool.log("点击首页")
            sleep(3000)
        } else {
            enterDouYinIndex()
        }
    } else {
        back()
        tool.log("返回")
        sleep(2000)
        enterDouYinIndex()
    }
}

var win;
//设置控制台
function setConsole () {
    win = floaty.rawWindow(
        <vertical h="200" w="400" bg="#000000" alpha="0.3">
            <text id="log" line="5" textColor="white" textSize="14sp" typeface="normal"></text>
        </vertical>
    );
    //悬浮穿透
    win.setTouchable(false);
    //悬浮移动
    win.setPosition(0, device.height / 4);
}

//输出日志到控制台
function log (data, type) {
    console.log(data)
    if (!type) {     //默认是info
        type = "info"
    }
    if (isOpenConsole) {
        //是否输出到界面
        let isShow = false
        if (debugMode && type === "debug") {
            isShow = true
        } else if (type === "info") {
            isShow = true
        }
        if (isShow) {
            threads.start(() => {
                ui.run(() => {
                    try {
                        let t = win.log.text()
                        let size = t.split("\n")
                        let v = ""
                        if (size.length > maxLine) {
                            for (let i = size.length - maxLine + 1; i < size.length - 1; i++) {
                                v += size[i] + "\n"
                            }
                        } else {
                            v = t
                        }
                        v += data + "\n"
                        // console.log(win.log)
                        win.log.setText(v);
                    } catch (e) {
                        console.log("输出日志异常:" + e)
                    }
                });
            })
        }
    }
}

function _press (x, y, time) {
    if (!time) {
        time = 100
    }
    press(x * bx, y * by, time)
}

//将秒转换成小时分钟秒
function formatSeconds (value) {
    let theTime = parseInt(value);// 秒
    let theTime1 = 0;// 分
    let theTime2 = 0;// 小时
    if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
            return theTime2 + "小时" + theTime1 + "分" + theTime + "秒";
        } else {
            return theTime1 + "分" + theTime + "秒";
        }
    } else {
        return theTime + "秒";
    }
}


//以图找图
function findImage (template, options) {
    let p = null;
    try {
        let base = captureScreen();
        template = images.read(`./image/${template}`);
        if (template == null) {
            tool.log("模板不存在")
        } else {
            p = images.findImage(base, template, options)
        }
    }
    catch (e) {
        tool.log(`找图异常:${e}`);
    }
    return p;
}

//重启app
function restartApp (t) {
    killApp(t)
    sleep(1000)
    openApp(t)
}

//打开app
function openApp (appName) {
    tool.log("打开应用：" + appName)
    launchApp(appName);
    sleep(2000)
    if (text("允许").exists()) {
        click("允许")
    }
    sleep(2000)
    if (text("打开").exists()) {
        click("打开")
    }
    sleep(1000)
    if (textContains("跳过").exists()) {
        clickText("跳过")
    }
}

//关闭app
// function killApp (appName) {
//     tool.log("关闭应用：" + appName)
//     launchApp(appName);
//     sleep(2000)
//     home();
//     sleep(1000)
//     recents()
//     sleep(1500)
//     swipe(device.width / 2 + 150, device.height / 2 - 200, device.width / 2 + 150, 50, 200)
//     sleep(1000)
//     home();
// }


//关闭app
function killApp (appName) {
    let forcedStopStr = ["确定", "结束", "停", "强行停止"];
    let packageName = app.getPackageName(appName);//获取应用包名 通过软件名
    if (packageName) {
        app.openAppSetting(packageName);//进入应用设置信息
        sleep(2000);
        if (textContains("停止").exists()) {
            let forcedStop = textContains("停止").findOne(2000).bounds();
            click(forcedStop.centerX() * bx, forcedStop.centerY() * by);
            // tool.log("停止app")
            sleep(2000);
        }
        for (let i = 0; i < forcedStopStr.length; i++) {
            if (text(forcedStopStr[i]).exists()) {
                let forcedStop = text(forcedStopStr[i]).findOne(2000).bounds();
                click(forcedStop.centerX() * bx, forcedStop.centerY() * by);
                // tool.log("确定停止")
                sleep(1000);
            }
        }
        home();
    }
}

//等待ID出现并点击
function clickId (ids, time) {
    try {
        time = time || 5000
        idContains(ids).findOne(5000)
        if (idContains(ids).exists()) {
            let p = idContains(ids).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() + 10, p.centerY(), 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//等待文本出现并点击
function clickText (t, time) {
    try {
        time = time || 5000
        text(t).findOne(time)
        if (text(t).exists()) {
            let p = text(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                click(parseInt(p.centerX() * bx), parseInt(p.centerY() * by));
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//等待文本出现并点击
function clickTextContains (t, time) {
    try {
        time = time || 5000
        textContains(t).findOne(time)
        if (textContains(t).exists()) {
            let p = textContains(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() * bx, p.centerY() * bx, 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//点击类名
function clickClassName (t, time) {
    try {
        time = time || 5000
        classNameContains(t).findOne(time)
        if (classNameContains(t).exists()) {
            let p = classNameContains(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() * bx, p.centerY() * bx, 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//等待描述出现并点击
function clickDesc (t, time) {
    try {
        time = time || 5000
        desc(t).findOne(time)
        if (desc(t).exists()) {
            let p = desc(t).findOne(1000)
            if (p != null) {
                console.log(p)
                p = p.bounds()
                console.log(p)
                tool.log(`点击${t},X:${p.centerX() * bx + 10},Y:${p.centerY() * by}`)
                _press(p.centerX(), p.centerY(),200);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//获取悬浮窗和录屏权限
function getScreenCapture () {
    let Thread = threads.start(function () {
        if (!floaty.checkPermission()) {
            // 没有悬浮窗权限，提示用户并跳转请求
            toast("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
            floaty.requestPermission();
            exit();
        } else {
            toastLog('已有悬浮窗权限');
            //由于系统间同意授权的文本不同，采用正则表达式
        }

        let Allow = textMatches(/(允许|立即开始|统一)/).findOne(10 * 1000);
        if (Allow) {
            Allow.click();
        }

    });
    if (!requestScreenCapture(false)) {
        tool.log("请求录屏权限失败");
        return false;
    } else {
        tool.log("已获得录屏权限");
        Thread.interrupt()
        return true;
    }

}


//系统提示音
function playRingtone (time, size) {
    var size = size || 6
    var time = time || 1000
    var musice = android.media.RingtoneManager.TYPE_NOTIFICATION
    var mp = new android.media.MediaPlayer(); device.setMusicVolume(size)
    mp.setDataSource(context, android.media.RingtoneManager.getDefaultUri(musice));
    mp.prepare();
    mp.start();
}



//判断是否中奖
function handleLotteryResult () {
    let lotteryResult = false;
    //判断是否中奖
    if (textContains("领取奖品").exists() || textContains("恭喜").exists()) {
        lotteryResult = true;
    } else {
        // tool.log("没有抽中福袋")
    }
    return lotteryResult;
}


//将文字对象转换为数组
function convertTextToArray (g) {
    let t = []
    for (let i = 0; i < g.length; i++) {
        let s = g[i]
        if (s.children === null) {
            t.push(s)
        } else {
            t = t.concat(convertTextToArray(s.children))
        }
    }
    return t;
}

//识别当前屏幕的文字
function getText (t) {
    let p = null;
    try {
        if (t === undefined || t === null) {
            t = '视频'
        }
        // requestScreenCapture(false);
        var img = captureScreen();
        let startfishTime = new Date().getTime();
        let res = gmlkit.ocr(img, "zh");
        res = convertTextToArray(res.children)
        // let res = paddle.ocr(img);
        let endfishTime = new Date().getTime();
        console.log("识别时间1：" + (endfishTime - startfishTime) + "ms");
        for (let i = 0; i < res.length; i++) {
            let text = res[i].text
            // tool.log(`文字:${text}-${t}:${text===t}`)
            if (text === t) {
                //tool.log("找到文字：" + JSON.stringify(res[i]));
                p = res[i]
                break;
            }
        }
        // img.recycle()
    } catch (e) {
        console.log(e)
    }
    return p;
}

//当前页面是否含有某个关键字
function hasText (t) {
    let p = false;
    try {
        if (t === undefined || t === null) {
            t = '视频'
            return p;
        }
        //当前屏幕截图
        let img = captureScreen();
        let startfishTime = new Date().getTime();
        let res = gmlkit.ocr(img, "zh");
        res = convertTextToArray(res.children)
        //  let res = paddle.ocr(img);
        let endfishTime = new Date().getTime();
        for (let i = 0; i < res.length; i++) {
            let text = res[i].text
            // tool.log(`文字:${text}-${t}:${text.includes(t)}`)
            if (text.includes(t)) {
                p = res[i]
                break;
            }
        }
        // img.recycle()
    } catch (e) {
        console.log(e)
    }
    return p;
}


//获取当前屏幕的文字,不分行
function getTextByScreenCapture (t) {
    let p = false;
    try {
        if (t === undefined || t === null) {
            t = '视频'
            return p;
        }
        let img = captureScreen();
        let res = gmlkit.ocr(img, "zh");
        res = res.children
        for (let i = 0; i < res.length; i++) {
            let text = res[i].text
            if (text.includes(t)) {
                p = res[i]
                break;
            }
        }
        img.recycle()
    } catch (e) {
        console.log(e)
    }
    return p;
}


//点击当前屏幕内的指定文字
function clickTextByScreenCapture (t) {
    let s = hasText(t)
    if (!s) {
        s = hasText(t)
        if (!s) {
            s = hasText(t)
            if (!s) {
                return false;
            } else {
                _press(s['bounds']['left'], s['bounds']['top'], 200)
                return true;
            }
        } else {
            _press(s['bounds']['left'], s['bounds']['top'], 200)
            return true;
        }
    } else {
        _press(s['bounds']['left'], s['bounds']['top'], 200)
        return true;
    }
}



//等待屏幕出现文字
function waitText (t, s) {
    if (!t) {
        t = 1000 * 10
    }
    let p = false;
    let startTime = new Date().getTime();
    do {
        if (new Date().getTime() - startTime > s) {
            console.log(`查找文字:${t}超时退出`)
            break;
        }
        p = hasText(t)
        if (p) {
            console.log(`找到文字:${t}了,p:${p}`)
            break;
        } else {
            console.log(`正在找文字:${t}`)
        }
        sleep(100)
    } while (true)
    sleep(500)
    return p;
}

// 获取剪贴板内容
function _getClip () {
    let text = '';
    threads.start(function () {
        var win = floaty.window(
            <vertical>
                <input id="输入" w="*" h="50" />
                <button id="开始" text="开始" />
            </vertical>
        )
        auto.setWindowFilter(function (window) {
            return true;
        });
        ui.run(() => {
            win.requestFocus();
            win.输入.requestFocus();
        })
        threads.start(function () {
            et = className("EditText").findOne();
            et.paste();
            text = win.输入.text()
            ui.run(() => {
                win.disableFocus();
            })
        })
    })
    sleep(500)
    return text;
}

exports.closeLinkPopup = closeLinkPopup;
exports.openHome2 = openHome2;
exports.getIdByUrl = getIdByUrl;
exports.getClip = _getClip;
exports.formatSeconds = formatSeconds;
exports.waitText = waitText;
exports.getTextByScreenCapture = getTextByScreenCapture;
exports.convertTextToArray = convertTextToArray
exports.setConsole = setConsole;
exports.findImage = findImage;
exports.restartApp = restartApp;
exports.openApp = openApp;
exports.killApp = killApp;
exports.clickId = clickId;
exports.clickText = clickText;
exports.clickDesc = clickDesc;
exports.getScreenCapture = getScreenCapture;
exports.playRingtone = playRingtone;
exports.handleLotteryResult = handleLotteryResult;
exports.clickClassName = clickClassName;
exports.getText = getText;
exports.init = init;
exports.clickTextByScreenCapture = clickTextByScreenCapture;
exports.enterDouYinIndex = enterDouYinIndex;
exports.log = log;
exports.press = _press;
exports.hasText = hasText;
exports.bx = bx;
exports.by = by;
exports.searchUser = searchUser;
exports.openHome = openHome;
